//
//  ZYZNetworkTool.swift
//  MyWeiBo
//
//  Created by 牛牛很牛 on 15/12/17.
//  Copyright © 2015年 曾勇召. All rights reserved.
//

import UIKit

import AFNetworking

//用枚举来管理错误,枚举既可以定义属性也可以定义方法
enum ZYZNetWorkError : Int {
    case emptyAccessToken = -1
    case emptyUid = -2
    
    //重写GET，计算性属性
    var errorDescripTion : String {
        get{
            switch self{
            case  ZYZNetWorkError.emptyAccessToken:
            return "access_token没有值"
            case ZYZNetWorkError.emptyUid:
            return "uid没有值"
            }
        }
    }
    
    //根据枚举返回错误
    func error( ) -> NSError {
    return NSError(domain: "ZYZWeibo.netWork.error", code: self.rawValue, userInfo: ["errorDescripTion" : self.errorDescripTion])
    }
}


class ZYZNetworkTool: AFHTTPSessionManager {
    
    //单例，默认的调用的构造函数
    static let shareNetworkTool1 : ZYZNetworkTool = ZYZNetworkTool()
    
    private init(){
        let  baseURL = NSURL(string : "https://api.weibo.com/")
        
    super.init(baseURL: baseURL, sessionConfiguration: nil)
        
        //设置相应的序列化器
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")

    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    private let client_id = "954617978"
     let redirect_uri = "http://www.baidu.com"
    let  client_secret = "a05c1821b0e59fda928c7f27106b47ef"
    let  grant_type = "authorization_code"
    

    func oauthURL() -> NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    
    }
    
    //加载accessToken
//请求成功时，使用闭包回调finished
    func loadAccesToken(code : String, finish: (result:[String: AnyObject]?, error:NSError?) -> ())  {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //参数,字典
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : grant_type,
            "code" : code,
            "redirect_uri" : redirect_uri
         ]
        
        //Post请求
        
        
        
        
        
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
         //调用闭包，将返回结果转成字典
            let dict = result as? [String:AnyObject]
            finish(result: dict, error: nil)
            }) { (_, error) -> Void in
                finish(result: nil, error: error)
                
        }
     
    }
    
    
    //加载用户信息
    func  loadUserInfo (finished:(result:[String : AnyObject]? , error : NSError?) ->()) {
        //获取acessToken
        guard let accessToken =   ZYZUserAcount.loadUserAccount()?.access_token else {
        //没有值就进来
            let error = ZYZNetWorkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        guard let uid = ZYZUserAcount.loadUserAccount()?.uid  else{
            let error = ZYZNetWorkError.emptyUid.error()
            finished(result: nil, error: error)
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //请求参数
        let paramters = [
            "access_token" : accessToken,
            "uid" : uid
        ]
        
        //get 请求
        
         GET(urlString, parameters: paramters, success: { (_, result) -> Void in
            let dict = result as? [String:AnyObject]
            // 调用闭包
            finished(result : dict , error : nil)
            }) { (_, error) -> Void in
            finished(result : nil , error : error)

        }
    
    }
  
    
    //MARK - 获取微博数据
    func loadStatus(finished:(result:[String : AnyObject]?, error:NSError?)->()) {
    //判断access-token
        guard let access_token = ZYZUserAcount.loadUserAccount()?.access_token  else{
        let  error = ZYZNetWorkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["access_token": access_token]
        //发送GET请求
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }

}
